﻿using System.ComponentModel;
using System.Net;

namespace WpfDownload
{
    /// <summary>
    /// A task is a process of downloading a Uri stored in a record using a webClient
    /// </summary>
    public class Task
    {
        private WebClient webClient;

        /// <summary>
        /// The record keeps information about this task
        /// </summary>
        public DownloadRecord Record { get; set; }

        /// <summary>
        /// Will be raised when the WebClient informs about any change
        /// </summary>
        public event DownloadProgressChangedEventHandler ProgressChanged;

        /// <summary>
        /// Will be raised when the task has been completed
        /// </summary>
        public event AsyncCompletedEventHandler Completed;

        public Task(DownloadRecord record)
        {
            this.Record = record;
						webClient = new WebClient();
        }

        public void Start()
        {
					if (webClient==null) return;

            // webClient.DownloadDataCompleted += webClient_DownloadDataCompleted;
            webClient.DownloadFileCompleted += DownloadFileCompleted;
            webClient.DownloadProgressChanged += DownloadProgressChanged;

						webClient.DownloadFileAsync(Record.Uri, string.Format("{0}\\{1}{2}", Record.DestinationFolder, Record.Prefix, Record.FileName));
        }

        void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            Record.Status = string.Format("Downloading {0}%", e.ProgressPercentage);
            if (ProgressChanged != null)
                ProgressChanged(this, e);
        }
        void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
                Record.Status ="Error: " +  e.Error.Message;
            else
               Record.Status = "Completed";


            webClient.DownloadFileCompleted -= DownloadFileCompleted;
						webClient.DownloadProgressChanged -= DownloadProgressChanged;
						webClient = null;
            if (Completed != null)
                Completed(this, e);
        }

        public void Stop()
        {
            if (webClient.IsBusy) return;
            webClient.CancelAsync();
            webClient.DownloadFileCompleted -= DownloadFileCompleted;
            webClient.DownloadProgressChanged -= DownloadProgressChanged;

        }

        /// <summary>
        /// Inidicates if the task is in action
        /// </summary>
        public bool IsBusy
				{ get { return webClient!=null && webClient.IsBusy; } }

    }
}
